﻿;(function ($) {

$.fn.addToCart = function (options) {

	if (this.length > 1) {
		this.each(function()  {
				var elm = $(this);
				elm.addToCart(options)
			}
		);
		return this;
	}

	var settings = {};
	var element = null;

	this.init = function() {

		element = $(this);
		settings = $.extend({} , $.fn.addToCart.defaultOptions, options);

		element.click(function() {
			var qty = $(settings.quantityElement).val();
			if (qty == null) {
				qty = 1;
			}
			var rel = $(this).attr('rel').split('|');
			addToCart(rel[0], qty, rel[1]);
			return false;
		});
		return this;
	};

	function addToCart(productCode, qty, addfrom) {

		settings.onloading.apply(element);

		$.ajax({
			type : 'POST',
			contentType : 'application/json',
			url : settings.url,
			data : JSON.stringify({ 
				productCode: productCode,
				quantity: qty,
				viewName: settings.viewName,
				from: addfrom
			}),
			success : function (data) {
				$(settings.dialogElement).empty();
				$(settings.dialogElement).html(data);
				$(settings.dialogElement).dialog('open');
				settings.onsuccess.apply(element);
			}
		});
	}

	return this.init();
};

$.fn.addToCart.defaultOptions = {
	dialogElement: null,
	quantityElement: null,
	url: null,
	viewName: null,
	onsuccess: function () { },
	onloading : function () { }
};

/*
 
 Show Cart Status

*/
$.fn.showCartStatus = function (options) {
	if (this.length > 1) {
		this.each(function()  {
				var elm = $(this);
				elm.showCartStatus(options)
			}
		);
		return this;
	}

	var settings = {};
	var element = null;

	this.init = function() {

		element = $(this);
		settings = $.extend({} , $.fn.showCartStatus.defaultOptions, options);

		showStatus();

		return this;
	}

	function showStatus() {
		$(element).empty();
		$.ajax({
			type : 'POST',
			contentType : 'application/json',
			url : settings.url,
			data : JSON.stringify({ viewName : settings.viewName }),
			success : function (html) {
				$(element).html(html);
			}
		});
	}

	return this.init();
};

$.fn.showCartStatus.defaultOptions = {
	url: null,
	viewName: '_status'
};

})(jQuery);
